package kr.hkit.androidcomplete01.ch12;

import kr.hkit.androidcomplete01.R;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class GridViewTest extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch12_gridviewtest);
		
		GridView grid = (GridView) findViewById(R.id.grid);
		ImageAdapter adapter = new ImageAdapter(this);
		grid.setAdapter(adapter);
		
		grid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Toast.makeText(GridViewTest.this, position+"번째 그림 선택", Toast.LENGTH_SHORT).show();
			}
		});
		
		
		
	}
	
	class ImageAdapter extends BaseAdapter{
		private Context mContext;
		
		int[] picture={
				R.drawable.airplane,
				R.drawable.dog,
				R.drawable.toycar,
				R.drawable.cloud,
				R.drawable.korandoc
		};
		

		public ImageAdapter(Context c) {
			super();
			mContext = c;
		}

		@Override
		public int getCount() {
			return 100;
		}

		@Override
		public Object getItem(int position) {
			return picture[position%5];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView;
			if (convertView==null){
				imageView = new ImageView(mContext);
				imageView.setLayoutParams(new GridView.LayoutParams(80,60));
				imageView.setAdjustViewBounds(false);
				imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
			}else{
				imageView = (ImageView) convertView;
			}
			
			imageView.setImageResource(picture[position % 5]);
			
			return imageView;
		}
	}
}

